﻿using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata.Builders;
using Ordering.Domain.AggregatesModel.OrderAggregate;
using System;
using System.Collections.Generic;
using System.Text;

namespace Ordering.Infrastructure.EntityConfigurations
{
    public class OrderEntityTypeConfiguration
        : IEntityTypeConfiguration<Order>
    {
        public void Configure(EntityTypeBuilder<Order> builder)
        {
            builder.ToTable("order", OrderingContext.DEFAULT_SCHEMA);

            builder.HasKey(ci => ci.Id);

            builder.Property(ci => ci.Id)
               .UseHiLo("orderseq", OrderingContext.DEFAULT_SCHEMA)
               .IsRequired();

            builder.Property(cb => cb.OrderType)
               .IsRequired(true);
            builder.Property(cb => cb.OrderNO)
               .HasMaxLength(50)
               .IsRequired(true);
            builder.Property(cb => cb.CreateTime)
               .IsRequired(true);
            builder.Property(cb => cb.AppointmentTime)
               .IsRequired(true);
            builder.Property(cb => cb.CustomerCode)
               .IsRequired(true);
            builder.Property(cb => cb.OrderStatusId)
               .IsRequired(true);
            builder.Property(cb => cb.Description)
                .HasMaxLength(500)
                .IsRequired(false);
            builder.Property(cb => cb.Remark)
                .HasMaxLength(500)
                .IsRequired(false);
            builder
                .OwnsOne(o => o.Address, a =>
                {
                    a.WithOwner();
                });
            //导航属性
            //var navigation = builder.Metadata.FindNavigation(nameof(Order.OrderItems));
            //navigation.SetPropertyAccessMode(PropertyAccessMode.Field);
            //set forekey
            builder.HasMany(b => b.OrderItems)
                .WithOne()
                .HasForeignKey("OrderId")
                .OnDelete(DeleteBehavior.Cascade);

            builder.HasOne(o => o.OrderStatus)
                .WithMany()
                .HasForeignKey("OrderStatusId");
        }
    }
}
